//roles 角色
//tmp 每一个规则
//hasPermission 判断一个角色是否有访问某个路由权限

// import { resolvePath } from "react-router-dom";

//如:admin  meta:roles:["admin","editor"]
function hasPermission(roles,route){
    console.log("hasPermission被调用了");
    if(route.meta && route.meta.roles){
        return roles.some(role=>route.meta.roles.includes(role))
    }else{
        //没有meta
        return true
    }
}

// routes  所有动态路由
//  roles  角色
export function filterAsyncRoutes(routes,roles){
    const res = []
     routes.forEach(route=>{
        const tmp = {
            ...route
        }
        if(hasPermission(roles,tmp)){
            if(tmp.children){
                tmp.children  = filterAsyncRoutes(tmp.children,roles)
            }
            console.log("filterAsyncRoutes被调用了");
            res.push(tmp)
        }
     })
     console.log("filterAsyncRoutes===================",res);
     return res
}
//generateRoutes 生成路由规则们
export function generateRoutes(asyncRoutes,roles){
    console.log(asyncRoutes);
    console.log(roles);
    return dispatch=>{
        console.log('调用了generateRoutes');
        let accessRoutes=[]
        //filterAsyncRoutes生成当前用户可以访问的路由规则们
        accessRoutes=filterAsyncRoutes(asyncRoutes,roles)
        localStorage.setItem("routes",JSON.stringify(accessRoutes))
        console.log(accessRoutes);
        //把路由规则们存储到redux
        dispatch({type:"USER_PERMISSION",payload:accessRoutes})
    }
}
